package jus.aor.mobilagent.hostel;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import jus.aor.mobilagent.kernel._Service;

public class Annuaire implements _Service<HashMap<String,String>> {

	private HashMap<String,String> listeNumero = new HashMap<String,String>();
	public Annuaire(Object[] arg0){
		DocumentBuilder docBuilder;
		NamedNodeMap attrs;
		try {
			//<Hotel localisation="Paris" name="Chaine0Hotel0"/>
			docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document doc = docBuilder.parse(new File((String) arg0[0]));
			for(Node item : iterable(doc,"Telephone")) {
				attrs = item.getAttributes();
				String numero = attrs.getNamedItem("numero").getNodeValue();
				String name = attrs.getNamedItem("name").getNodeValue();
				listeNumero.put(name, numero);
			}
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}		
	}
	@Override
	public HashMap<String,String> call(Object... params) throws IllegalArgumentException {
		HashSet<String> listeHotel = (HashSet<String>) params[0];
		HashMap<String,String> listeProv = new HashMap<String,String>();
		for(String s : listeHotel){
			listeProv.put(s, listeNumero.get(s));
		}
		return listeProv;
	}
	
	private static Iterable<Node> iterable(final Node racine, final String element){
		return new Iterable<Node>() {
			@Override
			public Iterator<Node> iterator(){
				return new Iterator<Node>() {
					NodeList nodelist;
					int current = 0, length;
					{ //init
						try{
							nodelist = ((Document)racine).getElementsByTagName(element);
						}catch(ClassCastException e){
							nodelist = ((Element)racine).getElementsByTagName(element);
						}
						length = nodelist.getLength();
					}
					@Override
					public boolean hasNext(){return current<length;}
					@Override
					public Node next(){return nodelist.item(current++);}
					@Override
					public void remove(){}
				};
			}
		};
	}
	


}
